package com.shujia.flink.state;

import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.connector.base.DeliveryGuarantee;
import org.apache.flink.connector.kafka.sink.KafkaRecordSerializationSchema;
import org.apache.flink.connector.kafka.sink.KafkaSink;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.Properties;

public class Demo2ExactlyOnce {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //指定状态后端
        //HashMapStateBackend: 将状态保存到TaskManager的内存中
        //EmbeddedRocksDBStateBackend :将状态保存早TaskManager的磁盘中
      /*  env.setStateBackend(new HashMapStateBackend());

        //1、开启checkpoint
        env.enableCheckpointing(20000);

        // 使用 externalized checkpoints，这样 checkpoint 在作业取消后仍就会被保留
        env.getCheckpointConfig().setExternalizedCheckpointCleanup(
                CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);

        //指定保存快照的位置
        env.getCheckpointConfig().setCheckpointStorage("hdfs://master:9000/flink/checkpoint");

*/
        //创建kafka source
        KafkaSource<String> source = KafkaSource.<String>builder()
                .setBootstrapServers("master:9092,node1:9092,node2:9092")//broker列表
                .setTopics("lines")//指定topic
                .setGroupId("Demo5KafkaSource")//指定消费者组，保证一条数据在一个组内只消费一次
                .setStartingOffsets(OffsetsInitializer.earliest())//指定起始消费的位置
                .setValueOnlyDeserializer(new SimpleStringSchema())
                .build();

        //使用kafka source 创建流（无界流）
        DataStream<String> linesDS = env
                .fromSource(source, WatermarkStrategy.noWatermarks(), "Kafka Source");


        //清洗加工
        DataStream<String> filterDS = linesDS.filter(word -> !"".equals(word));


        Properties properties = new Properties();
        //指定事务超时时间小于15分钟，要大于checkpoint间隔时间
        properties.setProperty("transaction.timeout.ms", 10 * 60 * 1000 + "");

        //创建kafka sink
        KafkaSink<String> sink = KafkaSink.<String>builder()
                .setBootstrapServers("master:9092,node1:9092,node2:9092")
                .setKafkaProducerConfig(properties)
                .setRecordSerializer(KafkaRecordSerializationSchema.builder()
                        .setTopic("filter")
                        .setValueSerializationSchema(new SimpleStringSchema())
                        .build()
                )
                //AT_LEAST_ONCE: 至少一次，会出现重复数据
                //EXACTLY_ONCE: 不会出现重复数据
                .setDeliverGuarantee(DeliveryGuarantee.EXACTLY_ONCE)//数据处理的语义
                .build();

        //将数据保存到kafka中
        filterDS.sinkTo(sink);

        env.execute();
    }
}
